/*
 * 	Flan.Zeng 2011-2016	http://git.oschina.net/signup?inviter=flan
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.flan.stock.net;


import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * 自定义Volley的Request对象，用于将请求来的Json数据直接转化为对象
 * @author flan
 * @date   2015年11月7日
 */
public class ObjectRequest<T> extends Request<T> {
	
	private Listener<T> successListener;
	private Gson gson;
	private Type mGsonType;
	
	public ObjectRequest(int method,Type type, String url,Listener<T> successListener, ErrorListener errorListener) {
		super(method, url, errorListener);
		
		this.successListener = successListener;
		this.gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
		//this.gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();// 不转换没有 @Expose 注解的字段   
		this.mGsonType = type;
	}

	@Override
	protected void deliverResponse(T response) {
		successListener.onResponse(response);
	}

	@Override
	protected Response<T> parseNetworkResponse(NetworkResponse response) {
		
		try {
			
			T result = null;
			
			String jsonStr = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
			result = gson.fromJson(jsonStr, mGsonType);
			
			return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			
			return Response.error(new ParseError(e));
		}
		
	}



}















